
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package HlavneOkno;

import DatabazoveOkno.DatabazoveOkno;
import Logger.Loggerclass;
import java.awt.event.MouseEvent;
import java.beans.PropertyVetoException;
import java.sql.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;

/**
 *
 * @author Riso-Desktop
 */
public class Okno extends javax.swing.JFrame {

    Loggerclass logger = new Loggerclass();
    Connection conn;
    DatabaseMetaData dbmd = null;
    String[] databazy;
    Object aktcesta = null;
    TreePath tp = null;
    String server = null;
    String port = null;
    String meno = null;
    String heslo = null;
    PripojenieKSer pripojeniekser = null;
    static public ArrayList<String> nazvyZobraz = new ArrayList<>();
    static public ArrayList<DatabazoveOkno> zobrazeneOkna = new ArrayList<>();

    /**
     * Creates new form Okno
     */
    public Okno() {
        initComponents();
        //this.setExtendedState(MAXIMIZED_BOTH);
        jTree1.setRootVisible(false);
    }

    private Connection pripojenie(String databaza) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://" + server + ":" + port + "/" + databaza, meno, heslo);
            dbmd = conn.getMetaData();
            return conn;
        } catch (Exception e) {
            Logger.getLogger("mojlog").log(Level.WARNING, e.toString(), e);
            return null;
        }
    }

    private void vypisDatabazu() {
        try {
            ResultSet rs = dbmd.getCatalogs();
            ResultSetMetaData rsmd = rs.getMetaData();
            rs.last();
            databazy = new String[rs.getRow()];
            rs.beforeFirst();
            int i = 0;
            while (rs.next()) {

                databazy[i] = rs.getString(1);
                i++;
            }

        } catch (SQLException ex) {
            Logger.getLogger("mojlog").log(Level.WARNING, ex.toString(), ex);
        }
    }

    private void nacitajmodel() {
        jTree1.setModel(new DefaultTreeModel(new DefaultMutableTreeNode("root")));
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) jTree1.getModel().getRoot();
        String meno = "";
        for (int i = 0; i < databazy.length; i++) {
            meno = databazy[i];
            DefaultMutableTreeNode novy = new DefaultMutableTreeNode(meno);
            root.add(novy);
        }
        jTree1.expandPath(new TreePath(root.getPath()));
        jTree1.setRootVisible(false);
    }

    //pridame okno do panelu
    public void addFrame(Connection conn) {
        DatabazoveOkno datok = new DatabazoveOkno(conn, this);
        datok.setVisible(true);
        jDesktopPane1.add(datok);
        zobrazeneOkna.add(datok);
        try {
            datok.setSelected(true);
            datok.moveToFront();
        } catch (PropertyVetoException ex) {
            Logger.getLogger("mojlog").log(Level.WARNING, ex.toString(), ex);
        }
    }

    public void addFrame(Connection conn, String meno) {
        DatabazoveOkno datok = new DatabazoveOkno(conn, this);
        datok.setVisible(true);
        jDesktopPane1.add(datok);
        zobrazeneOkna.add(datok);
        datok.ukazTab(meno);
        try {
            datok.setSelected(true);
            datok.moveToFront();
        } catch (PropertyVetoException ex) {
            Logger.getLogger("mojlog").log(Level.WARNING, ex.toString(), ex);
        }
    }

    private void oknoDopredu(String meno) {
        DatabazoveOkno pom = null;
        int i = 0;
        pom = zobrazeneOkna.get(i);
        while (!pom.getMeno().equals(meno)) {
            pom = zobrazeneOkna.get(i);
            i++;
        }
        try {
            pom.setSelected(true);
            pom.moveToFront();
        } catch (PropertyVetoException ex) {
            Logger.getLogger("mojlog").log(Level.WARNING, ex.toString(), ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        jButton1 = new javax.swing.JButton();
        jDesktopPane1 = new javax.swing.JDesktopPane();
        jToolBar2 = new javax.swing.JToolBar();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        jButton1.setText("Otvoriť pripojenie");
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton1);

        jToolBar2.setFloatable(false);
        jToolBar2.setRollover(true);

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("žiadne pripojenie");
        jTree1.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        jTree1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTree1MouseClicked(evt);
            }
        });
        jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                jTree1ValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jTree1);

        jMenu1.setText("File");

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText("Otvoriť novú databázu");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 805, Short.MAX_VALUE)
            .addComponent(jToolBar2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jDesktopPane1))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jDesktopPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 486, Short.MAX_VALUE)
                    .addComponent(jScrollPane1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        new PripojenieKDB(this).setVisible(true);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_jTree1ValueChanged
        try {
            aktcesta = evt.getNewLeadSelectionPath().getLastPathComponent();
            tp = evt.getPath();
        } catch (Exception e) {
        }
    }//GEN-LAST:event_jTree1ValueChanged

    private void jTree1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTree1MouseClicked
        MutableTreeNode jelist = (MutableTreeNode) aktcesta;
        tp = jTree1.getAnchorSelectionPath();
        //ak treba otvoriť pripojenie k databázy
        if (jelist != null && tp != null && evt.getClickCount() >= 2 && tp.getPathCount() < 3 && jelist.isLeaf()) {
            try {
                Connection con = pripojenie(aktcesta.toString());
                DatabaseMetaData dmd = con.getMetaData();
                String[] tabulky = {"TABLE"};
                String[] nazvytabuliek;
                ResultSet rs = dmd.getTables(null, null, null, tabulky);
                ResultSetMetaData rsmd = rs.getMetaData();
                rs.last();
                nazvytabuliek = new String[rs.getRow()];
                rs.beforeFirst();
                int i = 0;
                while (rs.next()) {
                    nazvytabuliek[i] = rs.getString(3);
                    i++;
                }
                MutableTreeNode node = (MutableTreeNode) aktcesta;
                DefaultMutableTreeNode root = (DefaultMutableTreeNode) jTree1.getModel().getRoot();
                DefaultTreeModel model = (DefaultTreeModel) jTree1.getModel();
                for (int l = 0; l < nazvytabuliek.length; l++) {
                    MutableTreeNode novy = new DefaultMutableTreeNode(nazvytabuliek[l]);
                    model.insertNodeInto(novy, node, node.getChildCount());
                }
                jTree1.setModel(model);
                jTree1.expandPath(tp);
            } catch (SQLException ex) {
                Logger.getLogger("mojlog").log(Level.WARNING, ex.toString(), ex);
            }
            //ak treba otvoriť tabuľku
        } else if (jelist != null && tp != null && evt.getClickCount() >= 2 && tp.getPathCount() == 3) {
            if (!nazvyZobraz.contains(tp.getLastPathComponent().toString())) {
                Object[] cesta = tp.getPath();
                conn = pripojenie(cesta[1].toString());
                this.addFrame(conn, tp.getLastPathComponent().toString());
                nazvyZobraz.add(tp.getLastPathComponent().toString());
            } else if(jelist != null && tp != null){
                oknoDopredu(tp.getLastPathComponent().toString()); //posunutie okna ak je už tabuľka otvorená
            }
        }
    }//GEN-LAST:event_jTree1MouseClicked

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (pripojeniekser == null) {
            pripojeniekser = new PripojenieKSer(this);
            pripojeniekser.setVisible(true);
            conn = pripojeniekser.getConnection();
            while (pripojeniekser.isVisible()) {
            }
            if(conn != null){
            try {
                dbmd = conn.getMetaData();
                server = pripojeniekser.getServer();
                port = pripojeniekser.getPort();
                meno = pripojeniekser.getMeno();
                heslo = pripojeniekser.getHeslo();
            } catch (SQLException ex) {
            }
            vypisDatabazu();
            nacitajmodel();
            }else{
                pripojeniekser = null;
            }
        } else {
            JOptionPane.showMessageDialog(this, "Už je naviazané spojenie s databázou");
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Okno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Okno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Okno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Okno.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Okno().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JDesktopPane jDesktopPane1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JToolBar jToolBar2;
    private javax.swing.JTree jTree1;
    // End of variables declaration//GEN-END:variables
}
